
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>5、_RocketMQ_高级特性 - 交互式测验</title>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
        
        body {
          font-family: 'Noto Sans SC', sans-serif;
          background-color: #f4f7f9;
          color: #333;
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          margin: 0;
          padding: 20px;
          box-sizing: border-box;
        }
        
        .main-wrapper {
            position: relative;
            width: 100%;
            max-width: 900px; /* Wider to accommodate buttons */
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .quiz-container {
          background-color: #ffffff;
          border-radius: 16px;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
          width: 100%;
          max-width: 700px;
          overflow: hidden;
          z-index: 10;
        }

        .quiz-header {
          background-color: #4a90e2;
          color: white;
          padding: 20px 30px;
          text-align: center;
        }

        .quiz-header h1 {
          margin: 0;
          font-size: 24px;
          font-weight: 700;
        }
        
        .quiz-header p {
            margin: 5px 0 0;
            font-size: 14px;
            opacity: 0.9;
        }

        .quiz-body {
          padding: 30px;
        }

        .progress-bar {
            display: none; /* 隐藏进度条 */
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 5px;
            height: 10px;
            margin-bottom: 20px;
        }

        #progress-indicator {
            height: 100%;
            width: 0%;
            background-color: #4caf50;
            border-radius: 5px;
            transition: width 0.3s ease;
        }

        #question-container {
          margin-bottom: 20px;
        }

        #question-text {
          font-size: 18px;
          font-weight: 500;
          line-height: 1.6;
          margin-bottom: 25px;
        }

        .options-list {
          list-style: none;
          padding: 0;
          margin: 0;
        }

        .option-item {
          background-color: #f8f9fa;
          border: 1px solid #dee2e6;
          border-radius: 8px;
          padding: 15px;
          margin-bottom: 12px;
          cursor: pointer;
          transition: background-color 0.2s ease, border-color 0.2s ease;
        }

        .option-item:hover {
          background-color: #e9ecef;
        }
        
        .option-item.selected {
            background-color: #d1e7fd;
            border-color: #4a90e2;
        }

        .quiz-footer {
          padding: 20px 30px;
          display: flex;
          justify-content: space-between; /* 将按钮分布在两侧 */
          align-items: center;
          min-height: 65px; /* Reserve space */
        }

        .nav-btn {
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 8px;
          padding: 10px 20px;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.2s ease, transform 0.2s ease;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        #next-btn {
            background-color: #28a745;
        }

        .nav-btn:hover {
          background-color: #357abd;
          transform: scale(1.05);
        }
        
        .nav-btn:disabled {
            background-color: #a0c3e8;
            cursor: not-allowed;
            opacity: 0.7;
        }

        #result-container {
            border-top: 1px solid #eee;
        }
        
        .result-box {
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .result-box.correct {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .result-box.incorrect {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .result-box h3 {
            margin-top: 0;
        }

        .explanation-text {
            margin-top: 15px;
            line-height: 1.7;
        }
        
        .source-text {
            font-style: italic;
            font-size: 14px;
            margin-top: 15px;
            color: #555;
        }

        
        .final-score-container {
            padding: 40px;
            text-align: center;
        }
        .final-score-container h2 {
            margin-top: 0;
            margin-bottom: 30px;
        }
        .score-summary {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 40px;
            flex-wrap: wrap;
        }
        .score-card {
            background-color: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            width: 180px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #e9ecef;
        }
        .score-card h3 {
            margin: 0 0 10px;
            font-size: 16px;
            font-weight: 500;
            color: #555;
        }
        .score-card p {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            color: #333;
        }
        .score-details table {
            width: 100%;
            font-size: 16px;
        }
        .score-details td {
            padding: 4px 0;
        }
        .score-details td:last-child {
            text-align: right;
            font-weight: 700;
        }
        .report-actions button {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 12px 25px;
            font-size: 16px;
            cursor: pointer;
            margin: 0 10px;
            transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
        }
        .report-actions button:hover {
            background-color: #f1f1f1;
            border-color: #bbb;
            transform: translateY(-2px);
        }
        .report-actions button.primary {
            background-color: #28a745;
            color: white;
            border-color: #28a745;
        }
        .report-actions button.primary:hover {
            background-color: #218838;
        }
        
        .hint-container {
            background-color: #e0f7fa;
            border: 1px solid #b2ebf2;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            color: #006064;
            font-size: 15px;
            line-height: 1.6;
            display: none; /* 默认隐藏 */
        }
      </style>
    </head>
    <body>
      <div class="main-wrapper">
          <div class="quiz-container">
            <div class="quiz-header">
              <h1>5、_RocketMQ_高级特性 - 交互式测验</h1>
              <p>检验你对文档内容的理解程度</p>
            </div>
            <div id="quiz-content">
                <div class="quiz-body">
                    <div class="progress-bar">
                        <div id="progress-indicator"></div>
                    </div>
                    <div id="question-container">
                      <p id="question-text"></p>
                      <ul class="options-list" id="options-list"></ul>
                    </div>
                    <div id="result-container"></div>
                    <div id="hint-container" class="hint-container"></div>
                </div>
                <div class="quiz-footer" id="quiz-footer">
                  <button id="prev-btn" class="nav-btn">上一题</button>
                  <button id="hint-btn" class="nav-btn" style="background-color: #ffc107; color: #333; box-shadow: 0 4px 12px rgba(255,193,7,0.3);">提示</button>
                  <button id="next-btn" class="nav-btn">下一题</button>
                </div>
            </div>
          </div>
      </div>

      <script>
        const quizData = [
  {
    "question": "在RocketMQ中，如果业务场景对消息的可靠性要求极高，即使牺牲部分性能也要确保消息不因Broker宕机而丢失，应该选择哪种刷盘策略？",
    "options": [
      "异步刷盘 (ASYNC_FLUSH)",
      "同步刷盘 (SYNC_FLUSH)",
      "内存映射 (MappedByteBuffer)",
      "同步双写 (SYNC_MASTER)"
    ],
    "correctAnswerIndex": 1,
    "explanation": "同步刷盘（SYNC_FLUSH）会在消息写入内存后，立即强制刷写到磁盘，并等待刷盘成功才向生产者返回确认。这种方式可以最大限度地保证即使Broker突然宕机，已经确认的消息也不会丢失，因此可靠性最高，但会牺牲一定的写入性能。",
    "source": "文档中「1. 消息一致性保证机制」下的「刷盘策略」部分",
    "hint": "文档中提到一种策略的优点是“消息不会因为Broker宕机而丢失”，而缺点是“性能较低”。"
  },
  {
    "question": "RocketMQ的“同步双写”主从复制策略（SYNC_MASTER）提供了极高的数据可靠性，其主要工作原理是什么？",
    "options": [
      "消息写入Master成功后立即返回成功，然后通过后台线程异步复制到所有Slave节点。",
      "消息会同时写入Master和所有Slave节点，谁先成功谁先返回确认。",
      "消息写入Master成功后，必须同步复制到Slave节点并收到确认后，才向生产者返回成功响应。",
      "消息只需要写入Master的内存即可返回成功，由操作系统负责后续的复制。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "“同步双写”策略要求消息不仅要成功写入Master，还必须被成功同步到一个Slave节点上之后，Broker才会向生产者返回成功确认。这确保了即使Master节点突然宕机，消息在Slave节点上依然有备份，从而避免了数据丢失。",
    "source": "文档中「1. 消息一致性保证机制」下的「主从复制策略」部分",
    "hint": "这种策略的优点是“保证数据不丢失，即使Master宕机”。"
  },
  {
    "question": "根据文档描述，在RocketMQ的集群消费（Cluster）模式和广播消费（Broadcast）模式下，消费位点（offset）的存储位置有何不同？",
    "options": [
      "集群模式下消费位点存储在Broker端，广播模式下存储在消费者本地。",
      "两种模式下消费位点都存储在Broker端，以实现统一管理。",
      "两种模式下消费位点都存储在消费者本地，以减轻Broker负担。",
      "集群模式下消费位点存储在消费者本地，广播模式下存储在Broker端。"
    ],
    "correctAnswerIndex": 0,
    "explanation": "在集群消费模式下，多个消费者共同消费一个队列，消费进度需要被所有消费者共享和协调，因此位点存储在Broker端。而在广播模式下，每个消费者都独立消费所有消息，各自维护自己的消费进度即可，所以位点存储在各自的本地。",
    "source": "文档中「1. 消息一致性保证机制」下的「消费进度管理」部分",
    "hint": "考虑一下哪种模式下，消费进度需要被同一个消费组内的多个实例共享。"
  },
  {
    "question": "RocketMQ的事务消息机制是如何实现分布式事务的最终一致性的？",
    "options": [
      "依赖消费端的幂等设计来保证事务的最终一致性。",
      "通过发送“半消息”（Half Message）和后续的事务状态回查机制。",
      "使用死信队列来处理所有失败的事务。",
      "通过全局顺序消费来确保事务的原子性。"
    ],
    "correctAnswerIndex": 1,
    "explanation": "RocketMQ的事务消息采用了两阶段提交的思想。第一阶段，生产者发送一个对消费者不可见的“半消息”。第二阶段，生产者执行本地事务。如果本地事务成功，则提交该“半消息”使其对消费者可见；如果失败，则回滚。若生产者未明确提交或回滚（如应用崩溃），Broker会定期回调生产者的接口（事务回查），来确定该“半消息”的最终状态，从而保证最终一致性。",
    "source": "文档中「1. 消息一致性保证机制」下的「事务消息」部分",
    "hint": "文档提到了“两阶段提交”和“定期检查半消息的状态”这两个关键步骤。"
  },
  {
    "question": "当监控到RocketMQ的“消息堆积量”持续增长时，根据文档建议，最直接和有效的排查方向是什么？",
    "options": [
      "检查Broker的磁盘IO是否达到瓶颈，并考虑更换更快的存储设备。",
      "检查生产者TPS是否过高，并考虑对生产者进行限流。",
      "检查消费者状态，例如是否正常运行、处理速度是否过慢，并考虑增加消费者实例。",
      "检查NameServer是否正常，以及路由信息是否准确。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "消息堆积的根本原因是消费速度跟不上生产速度。因此，首要的排查步骤是定位消费端的问题，比如消费者应用是否崩溃、是否存在处理逻辑耗时过长、或者消费者实例数量不足以应对当前的流量高峰。增加消费者实例是提高并行处理能力、解决堆积问题的常用手段。",
    "source": "文档中「2. 集群监控与运维最佳实践」下的「常见问题排查流程」中的「消息堆积」部分",
    "hint": "消息堆积意味着生产速度大于消费速度，问题的瓶颈最可能出现在哪个环节？"
  },
  {
    "question": "在RocketMQ中，当一条消息在消费时失败并经过多次自动重试后仍然不成功，它最终会被投递到哪里？",
    "options": [
      "被直接丢弃。",
      "返回给生产者。",
      "死信队列 (Dead-Letter Queue)。",
      "重试队列 (Retry Queue)。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "为了防止有问题的消息无限次重试从而阻塞整个队列，RocketMQ设计了死信队列机制。当一条消息达到最大重试次数后，如果仍然消费失败，它将被移入一个特殊的“死信队列”。这样可以隔离问题消息，保证正常消息的消费，同时开发人员可以订阅死信队列来对这些失败的消息进行人工干预或特殊处理。",
    "source": "文档中「1. 消息一致性保证机制」下的「消费重试机制」部分",
    "hint": "文档中提到，多次重试失败后，消息会进入一个队列“等待人工处理”。"
  },
  {
    "question": "某公司希望在同城的两个数据中心部署RocketMQ，实现业务双活，当一个机房故障时另一个机房能无缝接管，且所有组件在逻辑上属于同一个集群。应采用哪种部署模型？",
    "options": [
      "多集群部署",
      "单集群跨机房部署",
      "混合部署",
      "冷备份部署"
    ],
    "correctAnswerIndex": 1,
    "explanation": "单集群跨机房部署模型将一个逻辑集群的组件（如Master和Slave Broker）分布在不同的机房。这种架构提供了单一的集群视图，便于管理，并且通过主从切换可以实现机房级别的故障转移，非常适用于文档中描述的同城双活场景。",
    "source": "文档中「3. 跨机房/跨区域部署设计」下的「单集群跨机房部署」部分",
    "hint": "请注意题干中的关键信息：“单一集群逻辑视图”和“同城双活”。"
  },
  {
    "question": "在设计跨区域灾备方案时，哪种备份策略的实施成本最高，但能提供最快的恢复速度（RTO）和最小的数据丢失（RPO）？",
    "options": [
      "冷备份 (Cold Backup)",
      "温备份 (Warm Backup)",
      "热备份 (Hot Backup)",
      "半自动切换 (Semi-auto Switchover)"
    ],
    "correctAnswerIndex": 2,
    "explanation": "热备份策略要求备用区域的系统和数据与主区域保持实时同步，随时可以接管业务流量。这通常需要同步复制等技术来保证数据一致性，因此投入的资源和维护成本最高。但其优点是切换迅速，几乎可以做到零数据丢失，满足最苛刻的灾备要求。",
    "source": "文档中「3. 跨机房/跨区域部署设计」下的「灾备策略」部分",
    "hint": "文档中描述了一种策略的优缺点为：“几乎无数据丢失，切换迅速；缺点：成本高”。"
  }
];
        console.log("Quiz Data:", JSON.parse(JSON.stringify(quizData))); // 添加这行用于调试，以可展开的JSON格式输出
        
        let currentQuestionIndex = 0;
        let score = 0;
        // 存储每个问题的回答状态
        const userAnswers = new Array(quizData.length).fill(null); 

        const questionTextEl = document.getElementById('question-text');
        const optionsListEl = document.getElementById('options-list');
        const resultContainerEl = document.getElementById('result-container');
        const quizContentEl = document.getElementById('quiz-content');
        const progressIndicatorEl = document.getElementById('progress-indicator');
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const hintBtn = document.getElementById('hint-btn');
        const hintContainerEl = document.getElementById('hint-container');

        function loadQuestion() {
          resultContainerEl.innerHTML = '';
          optionsListEl.innerHTML = '';
          hintContainerEl.style.display = 'none'; // 隐藏提示
          
          if (currentQuestionIndex >= quizData.length) {
            showFinalScore();
            return;
          }

          updateProgress();

          const currentQuestion = quizData[currentQuestionIndex];
          questionTextEl.textContent = `(${currentQuestionIndex + 1}/${quizData.length}) ${currentQuestion.question}`;
          
          currentQuestion.options.forEach((optionText, index) => {
            const li = document.createElement('li');
            li.className = 'option-item';
            li.textContent = optionText;
            li.dataset.index = index; // Store index in a data attribute
            // 如果这道题已经回答过，恢复状态
            if (userAnswers[currentQuestionIndex] !== null) {
                if (index === userAnswers[currentQuestionIndex]) {
                    li.classList.add('selected');
                }
            }
            optionsListEl.appendChild(li);
          });

          // 如果已经回答过，直接显示结果
          if (userAnswers[currentQuestionIndex] !== null) {
              const isCorrect = userAnswers[currentQuestionIndex] === currentQuestion.correctAnswerIndex;
              showResult(isCorrect, currentQuestion);
          }
          
          updateNavigationButtons();
          updateProgress();
        }

        function selectOption(optionIndex) {
            userAnswers[currentQuestionIndex] = optionIndex;
            const currentQuestion = quizData[currentQuestionIndex];
            const isCorrect = optionIndex === currentQuestion.correctAnswerIndex;

            // 重新计算分数
            score = userAnswers.reduce((acc, answer, index) => {
                return answer === quizData[index].correctAnswerIndex ? acc + 1 : acc;
            }, 0);

            showResult(isCorrect, currentQuestion);
            updateNavigationButtons();
        }
        
        function updateProgress() {
            const answeredQuestions = userAnswers.filter(answer => answer !== null).length;
            const progressPercentage = (answeredQuestions / quizData.length) * 100;
            progressIndicatorEl.style.width = `${progressPercentage}%`;
        }
        
        function updateNavigationButtons() {
            prevBtn.style.display = 'block';
            nextBtn.style.display = 'block';
            hintBtn.style.display = 'block'; // 显示提示按钮

            prevBtn.disabled = currentQuestionIndex === 0;
            nextBtn.disabled = false; // 最后一题时，下一题按钮不禁用，而是用于显示报告
            nextBtn.textContent = (currentQuestionIndex === quizData.length - 1) ? '查看报告' : '下一题';
            
            // 如果当前问题没有提示，则禁用提示按钮并隐藏提示内容
            if (!quizData[currentQuestionIndex].hint) {
                hintBtn.disabled = true;
                hintContainerEl.style.display = 'none';
                hintContainerEl.textContent = ''; // 清除旧的提示内容
            } else {
                hintBtn.disabled = false;
            }
        }

        function showResult(isCorrect, questionData) {
            resultContainerEl.innerHTML = ''; // 清空之前的结果
            const resultBox = document.createElement('div');
            resultBox.className = `result-box ${isCorrect ? 'correct' : 'incorrect'}`;
            
            let html = `<h3>${isCorrect ? '回答正确！' : '回答错误'}</h3>`;
            if (!isCorrect) {
                html += `<p><strong>正确答案是：</strong> ${questionData.options[questionData.correctAnswerIndex]}</p>`;
            }
            html += `<div class="explanation-text">${questionData.explanation}</div>`;
            html += `<div class="source-text">来源: ${questionData.source}</div>`;
            
            resultBox.innerHTML = html;
            resultContainerEl.appendChild(resultBox);

            // 禁用所有选项的点击事件，并高亮正确/错误答案
            Array.from(optionsListEl.children).forEach((child, index) => {
                child.style.pointerEvents = 'none';
                // 高亮正确答案
                if (index === questionData.correctAnswerIndex) {
                    child.classList.add('correct'); // 需要添加CSS样式
                    child.style.backgroundColor = '#d4edda';
                    child.style.borderColor = '#c3e6cb';
                }
                // 如果选错了，高亮错误选项
                if (!isCorrect && index === userAnswers[currentQuestionIndex]) {
                    child.classList.add('incorrect'); // 需要添加CSS样式
                    child.style.backgroundColor = '#f8d7da';
                    child.style.borderColor = '#f5c6cb';
                }
            });
        }

        function goToNextQuestion() {
            if (currentQuestionIndex < quizData.length - 1) {
                currentQuestionIndex++;
                loadQuestion();
            } else {
                showFinalScore();
            }
        }

        function goToPreviousQuestion() {
            if (currentQuestionIndex > 0) {
                currentQuestionIndex--;
                loadQuestion();
            }
        }
        
        function showHint() {
            const currentQuestion = quizData[currentQuestionIndex];
            if (currentQuestion.hint) {
                hintContainerEl.textContent = currentQuestion.hint;
                hintContainerEl.style.display = 'block';
            } else {
                hintContainerEl.style.display = 'none';
            }
        }

        function showFinalScore() {
            document.querySelector('.quiz-body').style.display = 'none';
            document.getElementById('quiz-footer').style.display = 'none';

            const correctCount = score;
            const totalQuestions = quizData.length;
            const answeredCount = userAnswers.filter(a => a !== null).length;
            const wrongCount = answeredCount - correctCount;
            const skippedCount = totalQuestions - answeredCount;
            const accuracy = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0;
            const errorRate = totalQuestions > 0 ? Math.round((wrongCount / totalQuestions) * 100) : 0;

            const finalScoreHtml =
                '<div class="final-score-container">' +
                '<h2>答题报告</h2>' +
                '<div class="score-summary">' +
                '<div class="score-card">' +
                '<h3>得分</h3>' +
                '<p>' + correctCount + ' / ' + totalQuestions + '</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>正确率</h3>' +
                '<p>' + accuracy + '%</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>错误率</h3>' +
                '<p>' + errorRate + '%</p>' +
                '</div>' +
                '<div class="score-card score-details">' +
                '<table>' +
                '<tr><td>正确</td><td>' + correctCount + '</td></tr>' +
                '<tr><td>错误</td><td>' + wrongCount + '</td></tr>' +
                '<tr><td>未答</td><td>' + skippedCount + '</td></tr>' +
                '</table>' +
                '</div>' +
                '</div>' +
                '<div class="report-actions">' +
                '<button id="review-btn">回顾测验</button>' +
                '<button class="primary" onclick="location.reload()">再试一次</button>' +
                '</div>' +
                '</div>';

            let reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }
            quizContentEl.insertAdjacentHTML('beforeend', finalScoreHtml);
            document.getElementById('review-btn').addEventListener('click', reviewQuiz);
        }

        function reviewQuiz() {
            const reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }

            document.querySelector('.quiz-body').style.display = 'block';
            document.getElementById('quiz-footer').style.display = 'flex';
            
            currentQuestionIndex = 0;
            loadQuestion();
            updateNavigationButtons(); // Ensure nav buttons are correctly displayed
        }

        // Event Delegation for options
        optionsListEl.addEventListener('click', (event) => {
            if (event.target && event.target.matches('li.option-item')) {
                // Check if the question has already been answered
                if (userAnswers[currentQuestionIndex] === null) {
                    const selectedIndex = parseInt(event.target.dataset.index, 10);
                    selectOption(selectedIndex);
                }
            }
        });

        prevBtn.addEventListener('click', goToPreviousQuestion);
        nextBtn.addEventListener('click', goToNextQuestion);
        hintBtn.addEventListener('click', showHint);
        
        // 初始加载
        loadQuestion();
      </script>
    </body>
    </html>
  